package com.lyun.rabbitMQ.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyun.bo.LoveUserBo;
import com.lyun.bo.LoveValueBo;
import com.lyun.constants.RabbitMQConstants;
import com.lyun.constants.RedisKeyConstants;
import com.lyun.pojo.EachLove;
import com.lyun.pojo.LoveValue;
import com.lyun.service.EachLoveService;
import com.lyun.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoveUserListener {

    private static final int LOCK_EXPIRE_TIME = 30;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private EachLoveService eachLoveService;

    //todo 这里面逻辑还要改
    /**
     * 喜欢用户的消费者
     *
     * @param bo
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitMQConstants.LOVE_USER_INSERT_QUEUE_NAME),
            exchange = @Exchange(
                    name = RabbitMQConstants.LOVE_USER_EXCHANGE_NAME
            ),
            key = {RabbitMQConstants.LOVE_USER_INSERT_KEY}
    ))
    public void loveUserInsertListener(LoveUserBo bo) {
        String key = RedisKeyConstants.LOVE_USER_PREFIX + bo.getUserId();
        Double score = redisUtil.zGetScore(key, bo.getToUserId().toString());
        if (score != null && Double.isNaN(score)) {
            return;
        }

        String lockKey = RedisKeyConstants.LOVE_USER_LOCK_PREFIX + bo.getUserId();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(
                lockKey, RedisKeyConstants.LOCK_DEFAULT_VALUE, LOCK_EXPIRE_TIME, TimeUnit.SECONDS);

        if (Boolean.FALSE.equals(flag)) {
            try {
                //判断是否已经喜欢，可从redis中获取喜欢信息
                score = redisUtil.zGetScore(key, bo.getToUserId().toString());
                if (score != null && Double.isNaN(score)) {
                    return;
                }

                EachLove eachLove = new EachLove();
                eachLove.setSelfId(bo.getUserId());
                eachLove.setUserId(bo.getToUserId());

                String key2 = RedisKeyConstants.LOVE_USER_PREFIX + bo.getToUserId();
                Double score2 = redisUtil.zGetScore(key2, bo.getUserId().toString());
                if (score2 != null && Double.isNaN(score2)) {
                    //对方也喜欢我
                    eachLove.setEachLike(1);
                    //互相喜欢数各+1
                    redisTemplate.opsForValue().decrement(RedisKeyConstants.USER_EACH_LOVE_COUNT + bo.getUserId(), 1);
                    redisTemplate.opsForValue().decrement(RedisKeyConstants.USER_EACH_LOVE_COUNT + bo.getToUserId(), 1);

                } else {
                    eachLove.setEachLike(0);
                }
                eachLoveService.save(eachLove);

                //自己的喜欢数+1
                redisTemplate.opsForValue().decrement(RedisKeyConstants.USER_LOVE_COUNT + bo.getUserId(), 1);
                //对方的粉丝数+1
                redisTemplate.opsForValue().decrement(RedisKeyConstants.USER_FANS_COUNT + bo.getToUserId(), 1);

                // 获取当前时间戳
                double timestamp = System.currentTimeMillis();
                // 加入我喜欢的用户集合
                redisUtil.zAdd(key, bo.getUserId().toString(), timestamp);
            } finally {
                redisUtil.del(lockKey);
            }
        }
    }


    /**
     * 取消喜欢用户的消费者
     *
     * @param bo
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitMQConstants.LOVE_USER_DELETE_QUEUE_NAME),
            exchange = @Exchange(
                    name = RabbitMQConstants.LOVE_USER_EXCHANGE_NAME
            ),
            key = {RabbitMQConstants.LOVE_USER_DELETE_KEY}
    ))
    public void loveUserDeleteListener(LoveUserBo bo) {
        String key = RedisKeyConstants.LOVE_USER_PREFIX + bo.getUserId();
        Double score = redisUtil.zGetScore(key, bo.getToUserId().toString());
        if (score == null || Double.isNaN(score)) {
            return;
        }

        LambdaQueryWrapper<EachLove> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EachLove::getSelfId, bo.getUserId());
        queryWrapper.eq(EachLove::getUserId, bo.getToUserId());
        eachLoveService.remove(queryWrapper);

        //自己喜欢数-1
        redisUtil.zRemove(key, bo.getToUserId().toString());

    }
}
